//
//  PayViewController.m
//  Molian
//
//  Created by 胡津 on 1/7/15.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#import "PayViewController.h"
#import "PayTableViewCell.h"
#import <IAPShare.h>
#import "NSData+Base64.h"
#import "WalletRecordViewController.h"
@interface PayViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong)IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *rechargeBtnArray;

@property NSUInteger selectedRechargeIndex;

@property NSArray *productIdentifiers;

@property NSArray *rechargeMoneys;
@end

@implementation PayViewController
{
    NSArray *dataArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"充值";
    if ([Utils cheackConfigurationChangeImage]) {
         self.titleImageView.hidden = NO;
    }else{
        self.titleImageView.frame = CGRectZero;
    }
    // 默认选中6元
    self.selectedRechargeIndex = 0;
    
    self.productIdentifiers = @[IAP_ID_6_YUAN, IAP_ID_18_YUAN, IAP_ID_30_YUAN, IAP_ID_60_YUAN, IAP_ID_108_YUAN, IAP_ID_488_YUAN];
    self.rechargeMoneys = @[@4.2, @12.6, @21.0, @42.0, @75.6, @341.6];
    
    dataArr = @[@{@"PayTitle":@"40时光",@"Paydescribe":@"+ 送2时光",@"Pay":@"￥ 6"},@{@"PayTitle":@"120时光",@"Paydescribe":@"+ 送6时光",@"Pay":@"￥ 18"},@{@"PayTitle":@"200时光",@"Paydescribe":@"+ 送10时光",@"Pay":@"￥ 30"},@{@"PayTitle":@"400时光",@"Paydescribe":@"+ 送20时光",@"Pay":@"￥ 60"},@{@"PayTitle":@"720时光",@"Paydescribe":@"+ 送36时光",@"Pay":@"￥ 108"},@{@"PayTitle":@"3260时光",@"Paydescribe":@"+ 送156时光",@"Pay":@"￥ 488"}];
    
    _tableView.backgroundColor = [UIColor whiteColor];
    [_tableView registerNib:[UINib nibWithNibName:@"PayTableViewCell" bundle:nil] forCellReuseIdentifier:@"PayTableViewCell"];

    if ([Utils cheackConfigurationChangeImage]) {
        self.titleImageView.hidden = NO;
        
    }else{
        self.titleImageView.hidden = YES;
        
    }
    // 初始化IAP
    if (![IAPShare sharedHelper].iap.products) {
        [self initIAP];
    }
    
    UIButton *ringetBt = [UIButton buttonWithType:UIButtonTypeCustom];
    [ringetBt sizeToFit];
    [ringetBt setTitle:@"充值记录" forState:UIControlStateNormal];
    ringetBt.titleLabel.font = kFont(15);
    ringetBt.frame = CGRectMake(0, 0, 60, 30);
    ringetBt.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    [ringetBt addTarget:self action:@selector(clickRingetBt) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *ringetBatBt = [[UIBarButtonItem alloc] initWithCustomView:ringetBt];
    self.navigationItem.rightBarButtonItem = ringetBatBt;
   // [self inspectWebpage];
}
- (void)clickRingetBt
{
    
    WalletRecordViewController *walletRVC = [[WalletRecordViewController alloc] init];
    walletRVC.title = @"充值记录";
    [self.navigationController pushViewController:walletRVC animated:YES];
}
//充值失败的时候调用
 //检查是否可以网页充值
- (void)inspectWebpage
{
    //检查是否可以网页充值
    AVQuery *query = [MLWebpageRecharge query];
    [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        if (error) {
            
        }else{
    
            MLWebpageRecharge *webpagRecharge = (MLWebpageRecharge *)object;
            NSLog(@"%@",object);
            if (webpagRecharge&&webpagRecharge.normal&&webpagRecharge.normal == 1) {
                
                //网页正常
                NSString *text= [NSString stringWithFormat:@"%@%@?molianId=%ld",webpagRecharge.content,webpagRecharge.webpage,(long)[MLUser currentUser].molianId];
                //mlsystem给口袋君发消息
                NSDictionary *params = @{@"touserId": [MLUser currentUser].objectId,@"msg":text};
                [AVCloud callFunctionInBackground:@"sendSysMsg" withParameters:params block:^(id object, NSError *error) {
                    
                }];
            }else{
               
            }
        }
    }];}
// 初始化内购
- (void)initIAP {
    if(![IAPShare sharedHelper].iap) {
        NSSet *dataSet = [[NSSet alloc]initWithArray:self.productIdentifiers];
        [IAPShare sharedHelper].iap = [[IAPHelper alloc] initWithProductIdentifiers:dataSet];
    }
    [HUD setOnViewWithTitle:@"" animated:YES];
    
    [IAPShare sharedHelper].iap.production = NO;
    [[IAPShare sharedHelper].iap requestProductsWithCompletion:^(SKProductsRequest *request,SKProductsResponse *response)
     {
         [HUD hideFromViewAnimated:YES];
         if (response > 0) {
             NSLog(@"get products succeed");
         } else {
             NSLog(@"get products faild");
             [HUD Prompt:@"支付项加载失败,请退出页面再重试"];
             [self inspectWebpage];
         }
     }];
}

#pragma mark - tableview delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    

    if (indexPath.section == 0) {
        static  NSString *CellIdentifier = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if  (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        }
        
         cell.imageView.image = [UIImage imageNamed:@"icon_my_balance"];
        CGRect rect = cell.textLabel.frame;
        rect.origin.x -= 30;
        cell.textLabel.frame = rect;
        cell.textLabel.text = @"我的余额";
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%.0f时光",([MLUser currentUser].balance*10)];
        return cell;
        
    }else{
        PayTableViewCell*cell=(PayTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"PayTableViewCell"];

        cell.PayTitle.text = [[dataArr objectAtIndex:indexPath.row] objectForKey:@"PayTitle"];
        cell.Paydescribe.text = [[dataArr objectAtIndex:indexPath.row] objectForKey:@"Paydescribe"];
        [cell.Pay setTitle:[[dataArr objectAtIndex:indexPath.row] objectForKey:@"Pay"] forState:UIControlStateNormal];
        [cell.Pay addTarget:self action:@selector(Chongzhi:) forControlEvents:UIControlEventTouchUpInside];
        cell.Pay.tag = indexPath.row;
        
        return  cell;

    }

    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

-(void)Chongzhi:(UIButton*)sender
{
    self.selectedRechargeIndex = sender.tag;
    [self rechargeMoneyAtIndex];
}

// 执行充值
- (void)rechargeMoneyAtIndex{
    [AVAnalytics event:@"我的钱包充值"]; // 通知服务器一个点击事件。

     if ([MobClick isJailbroken]) {
     [HUD Prompt:@"越狱设备当前不支持该方式充值"];
         [self inspectWebpage];
         [AVAnalytics event:@"我的钱包充值(越狱设备)"]; // 通知服务器一个点击事件。
     return;
     }
    
    
    // 执行充值
    IAPHelper *iap = [IAPShare sharedHelper].iap;
    NSArray *products = iap.products;
    if (!products || [products count] == 0) {
        [HUD Prompt:@"支付项加载失败,请退出页面再重试"];
        [self inspectWebpage];
        return;
    }
    // 找到指定的product
    NSString *identifier = self.productIdentifiers[self.selectedRechargeIndex];
    NSString *rechargeMoney = self.rechargeMoneys[self.selectedRechargeIndex];
    SKProduct *selectProduct;
    for (SKProduct *product in products) {
        if ([product.productIdentifier isEqualToString:identifier]) {
            selectProduct = product;
            break;
        }
    }
    
    
    [HUD setOnViewWithTitle:@"正在交易..." animated:YES];
    [[IAPShare sharedHelper].iap buyProduct:selectProduct onCompletion:^(SKPaymentTransaction *transcation) {
        [HUD hideFromViewAnimated:YES];
        if (transcation.error) {
            NSLog(@"Fail %@", [transcation.error localizedDescription]);
            //[self verifyPruchase];
            [self inspectWebpage];
        } else if (transcation.transactionState  ==  SKPaymentTransactionStatePurchased) {
            //[self verifyPruchase];
            [HUD setOnViewWithTitle:@"支付结果确认中" animated:YES];
            // 服务器验证支付是否成功
            NSData *transactionReceipt = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]];
            //NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:transactionReceipt options:1 error:nil];
            //NSLog(@"%@",dic);
            NSDictionary *verifyParams = @{
                                           @"receipt": [transactionReceipt base64EncodedStringWithOptions:0],
                                           @"rechargeMoney": rechargeMoney,
                                           @"userId": [MLUser currentUser].objectId};
            [AVCloud callFunctionInBackground:@"verifyIAPReceipt" withParameters:verifyParams block:^(id object, NSError *error) {
                [HUD hideFromViewAnimated:YES];
                if (!error) {
                    // TODO 提示充值成功
                    // 充值成功, 刷新用户
                    [[MLUser currentUser] refreshInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                        [self.tableView reloadData];
                    }];
                    [HUD Prompt:@"充值成功"];
                } else {
                    [self inspectWebpage];
                    [HUD Prompt:@"充值失败,请重试"];
                    NSLog(@"充值失败");
                }
            }];
            // 将交易从交易队列中删除
            [[SKPaymentQueue defaultQueue] finishTransaction:transcation];
        } else if (transcation.transactionState  ==  SKPaymentTransactionStateFailed) {
            [HUD Prompt:@"充值失败,请重试"];
            [self inspectWebpage];
        }
    }];
}

#pragma mark 验证购买凭据
- (void)verifyPruchase
{
    // 验证凭据，获取到苹果返回的交易凭据
    // appStoreReceiptURL iOS7.0增加的，购买交易完成后，会将凭据存放在该地址
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    // 从沙盒中获取到购买凭据
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
    
    // 发送网络POST请求，对购买凭据进行验证
    NSURL *url = [NSURL URLWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"];
    // 国内访问苹果服务器比较慢，timeoutInterval需要长一点
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
    
    request.HTTPMethod = @"POST";
    
    // 在网络中传输数据，大多情况下是传输的字符串而不是二进制数据
    // 传输的是BASE64编码的字符串
    /**
     BASE64 常用的编码方案，通常用于数据传输，以及加密算法的基础算法，传输过程中能够保证数据传输的稳定性
     BASE64是可以编码和解码的
     */
    NSString *encodeStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    
    NSString *payload = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", encodeStr];
    NSData *payloadData = [payload dataUsingEncoding:NSUTF8StringEncoding];
    
    request.HTTPBody = payloadData;
    
    // 提交验证请求，并获得官方的验证JSON结果
    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    // 官方验证结果为空
    if (result == nil) {
        NSLog(@"验证失败");
    }
    
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingAllowFragments error:nil];
    
    NSLog(@"%@", dict);
    
    if (dict != nil) {
        // 比对字典中以下信息基本上可以保证数据安全
        // bundle_id&application_version&product_id&transaction_id
        NSLog(@"验证成功%@",dict);
    }
}


//section个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

//cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        return dataArr.count;
    }
}

//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0 ) {
        return 0.11111;
    }else{
        return 10;//每个cell的头部间距
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
{
    return 10;//每个cell的底部间距
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}

@end
